import {
  Attributes,
  FindOptions,
  ModelStatic,
  Model,
  ModelCtor
} from 'sequelize'
import { sequelize } from './connect'

/**
 * 找到所有数据
 * @param this
 * @param options
 * @returns
 */
export function findAllValues<M extends Model>(
  this: ModelStatic<M>,
  options?: FindOptions<Attributes<M>>
): Promise<Attributes<M>[]> {
  return this.findAll({
    ...options,
    raw: true
  })
}

/**
 * 找到一条数据
 * @param this
 * @param options
 * @returns
 */
export function findOneValue<M extends Model>(
  this: ModelStatic<M>,
  options?: FindOptions<Attributes<M>>
): Promise<Attributes<M>> {
  return this.findOne({
    ...options,
    raw: true
  })
}

/**
 * 随机找到一条数据
 * @param this
 * @param options
 * @returns
 */
export function findOneRandomValue<M extends Model>(
  this: ModelStatic<M>,
  options?: FindOptions<Attributes<M>>
): Promise<Attributes<M>> {
  return this.findOne({
    ...options,
    order: sequelize.random(),
    raw: true
  })
}

/**
 * 获取模型的属性类型
 */
export type AttributesModel<T extends ModelCtor<Model>> =
  T extends ModelCtor<infer M>
    ? M extends Model<infer U, object>
      ? U
      : never
    : never
